package android.demo.download;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;

public class NetworkManager {
	
	private BufferedReader in = null;
	private String result = null;
	private HttpClient client = null;
	private NetworkObserver observer = null;
	private boolean isGetMethod = true;
	private String url = ""; 
	private List<NameValuePair> postParameters = null;
	public static final int NONE_REQUEST_CODE = -1;
	private int mRequestCode = NONE_REQUEST_CODE;
	private Context context;
	private ProgressDialog processDialog = null;
			
	public NetworkManager() {
		client = new DefaultHttpClient();
		result = "";
	}
	
	public boolean isGetMethod() {
		return isGetMethod;
	}

	public void setGetMethod(boolean isGetMethod) {
		this.isGetMethod = isGetMethod;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public List<NameValuePair> getPostParameters() {
		return postParameters;
	}

	public void setPostParameters(List<NameValuePair> postParameters) {
		this.postParameters = postParameters;
	}

	public NetworkObserver getObserver() {
		return observer;
	}
	
	public void setObserver(NetworkObserver observer) {
		this.observer = observer;
	}
	
	public void unregisterObserver(){
		this.observer = null;
	}

	public void release(){
		client = null;
		result = null;
		observer = null;
		postParameters = null;
		url = null;
	}

	public void executeRequest(){
		
		// Declare new Thread use to excute HTTP request.
		Thread thread = new Thread(){
			public void run() {
				
				// Execute http request.
				try {
					
					if(isGetMethod)
						executeHttpGet();
					else 
						executeHttpPost();
				
				} catch (Exception e) {
					e.printStackTrace();
					//Notify error to observer
					SPIError error = new SPIError();
					error.setErrorCode(String.valueOf(999));
					error.setErrorDescription(e.getMessage());
					if(observer!=null)
						observer.onReceiveNetworkError(mRequestCode,error);
				}
				
				//Notify result to observer
				if(observer!=null)
					observer.onReceiveRerult(mRequestCode,result);
			};
		};
		
		// Start Thread.
		thread.start();
	}
	
	public void executeHttpPost() throws Exception {
		
		try {
			HttpPost request = new HttpPost(url);
			if(postParameters!=null){
				UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
				request.setEntity(formEntity);
			}
			HttpResponse response = client.execute(request);
			int statusCode = response.getStatusLine().getStatusCode();
			if(statusCode!=HttpStatus.SC_OK){
				observer.onReceiveNetworkError(mRequestCode,SPIError.genNetworkError(statusCode));
				return;
			}
			in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			StringBuffer sb = new StringBuffer("");
			String line = "";
			String NL = System.getProperty("line.separator");
			while ( (line = in.readLine()) != null) {
				sb.append(line + NL);
			}
			in.close();
			result = sb.toString();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		return;
	}

	public void executeHttpGet() throws Exception {
		BufferedReader in = null;
		try {
			HttpClient client = new DefaultHttpClient();
			HttpGet request = new HttpGet();
			request.setURI(new URI(url));
			HttpResponse response = client.execute(request);
			
			int statusCode = response.getStatusLine().getStatusCode();
			
			if(statusCode!=HttpStatus.SC_OK){
				observer.onReceiveNetworkError(mRequestCode,SPIError.genNetworkError(statusCode));
				return;
			}
			
			in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			StringBuffer sb = new StringBuffer("");
			String line = "";
			String NL = System.getProperty("line.separator");
			while ( (line = in.readLine()) != null) {
				sb.append(line + NL);
			}
			in.close();
			result = sb.toString();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return;
	}
	
	public void downloadFileInThread(int requestCode, String urlStr, String fileName, Context context){
		this.mRequestCode = requestCode;
		
	}
	
}
